package com.bangdream.michelia.view.activity.curriculum;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.TrainPlanContract;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.TaskCurriculumBean;
import com.bangdream.michelia.entity.TrainPlanBean;
import com.bangdream.michelia.entity.TrainPlanDetail;
import com.bangdream.michelia.presenter.TrainPlanPresenter;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.ImageLoadUtils;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.bangdream.michelia.view.activity.exam.ExamExplainActivity;
import com.bangdream.michelia.view.activity.exam.ExamInfoActivity;
import com.bangdream.michelia.view.activity.questionnaire.QuestionnaireActivity;
import com.bangdream.michelia.view.adapter.TrainPlanDetailAdapter;
import com.nanchen.compresshelper.StringUtil;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class TrainPlanDetailActivity extends SwipeBackActivity<TrainPlanContract.ITrainPlanView, TrainPlanPresenter<TrainPlanContract.ITrainPlanView>>
        implements TrainPlanContract.ITrainPlanView {
    TextView tvTrainDev, tv_title,tvState;
    RecyclerView recyclerView;
    ImageView iv_pic;
    LinearLayoutManager linearLayoutManager;
    TrainPlanDetailAdapter adapter;
    boolean isLearningOrder=false;
    String planUser="";
    String trainId;

    @Override
    public int getLayout() {
        return R.layout.train_detail;
    }

    @Override
    public void findId() {
        trainId = getIntent().getStringExtra("trainId");
        tvTrainDev = findViewById(R.id.tvTrainDev);
        tv_title = findViewById(R.id.tv_title);
        iv_pic = findViewById(R.id.iv_pic);
        tvState = findViewById(R.id.tvState);
        GradientDrawable background = (GradientDrawable) tvState.getBackground();
        background.setColor(Color.parseColor("#ff0000"));
        recyclerView = findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new TrainPlanDetailAdapter(R.layout.item_train_detail);
        recyclerView.setAdapter(adapter);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        RichText.initCacheDir(TrainPlanDetailActivity.this);

        adapter.setOnItemClickListener((a, view, position) -> {
            String type = adapter.getData().get(position).getType();
            String itemId = adapter.getData().get(position).getItemId();
            String planId = adapter.getData().get(position).getPlanId();
            String courseName = adapter.getData().get(position).getName();

            if(type!=null){
                if(isLearningOrder){
                    checkLearning(itemId,planId,type,courseName,position);
                }else{
                    jump(type,itemId,courseName,position);
                }
            }
        });

        //补考
        adapter.setOnItemChildClickListener((a, view, position) -> {
            String examId = adapter.getData().get(position).getExamId();
            if(StringUtil.isEmpty(examId)){
                ToastUtil.showShortToast(this,"数据异常");
            }else{
                Intent intent = new Intent(this,ExamExplainActivity.class);
                intent.putExtra("examId",adapter.getData().get(position).getExamId());
                intent.putExtra("itemId",adapter.getData().get(position).getItemId());
                intent.putExtra("planUserItemId",adapter.getData().get(position).getPlanUserItemId());
                startActivity(intent);
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getTrainPlanDetails(trainId, pd);
    }

    private void checkLearning(String itemId, String planId, String type, String coursName, int position){

        pd.show();
        Map map = new HashMap();

        map.put("id", planUser);
        map.put("planId", planId);//课程id
        map.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(map));

        RetroFactory.getInstance().checkLearningSequence(itemId,AppCurrentUser.getInstance().getToken(),requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseEntity s) {
                        pd.cancel();
                        if(s.getData()!=null && s.getData().toString().equals("true")){
                            jump(type,itemId,coursName, position);
                        }else{
                            ToastUtil.showShortToast(TrainPlanDetailActivity.this,"请先学习上级内容");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        pd.cancel();
                        ToastUtil.showShortToast(TrainPlanDetailActivity.this,"请求失败");

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void jump(String type, String itemId, String coureName, int position){
        switch (type){
            case "00"://课程
                Intent intent = new Intent(TrainPlanDetailActivity.this, CurriculumDetails.class);
                intent.putExtra("id", itemId);
                intent.putExtra("title",coureName);
                startActivity(intent);
                break;
            case "01"://考试
                Intent intent1 = new Intent(TrainPlanDetailActivity.this, ExamInfoActivity.class);
                intent1.putExtra("examId",itemId);
                intent1.putExtra("itemId",adapter.getData().get(position).getItemId());
                intent1.putExtra("planUserItemId",adapter.getData().get(position).getPlanUserItemId());
                intent1.putExtra("examResult",adapter.getData().get(position).getResult());
                startActivity(intent1);
                break;
            case "02"://问卷
                Intent intent2 = new Intent(TrainPlanDetailActivity.this, QuestionnaireActivity.class);
                intent2.putExtra("id",itemId);
                intent2.putExtra("paperId",itemId);
                intent2.putExtra("title",coureName);
                intent2.putExtra("planUserItemId",adapter.getData().get(position).getPlanUserItemId());
                startActivity(intent2);
                break;

        }
    }



    @Override
    public void setListener() {

    }

    @Override
    public void logic() {
    }


    @Override
    public TrainPlanPresenter createPresenter() {
        return new TrainPlanPresenter();
    }

    @Override
    public void setTrainPlanList(boolean isSuccess, int page, List<TrainPlanBean> data, String stDescribe) {

    }

    @Override
    public void setTrainPlanDetails(boolean isSuccess, TrainPlanDetail data) {

        if (isSuccess && data != null) {
            TrainPlanDetail.TrainingPlanBean trainingPlan = data.getTrainingPlan();
            //learningOrder 学习顺序（0-顺序学习，1-无序学习）
            String learningOrder = trainingPlan.getLearningOrder();
            isLearningOrder=learningOrder.equals("0");
            planUser=data.getId();
            if (trainingPlan != null) {
                tv_title.setText(trainingPlan.getTitle()+"");
                RichText.from(trainingPlan.getDescription()+"")
                        .autoPlay(true) // gif图片是否自动播放
                        .scaleType(ImageHolder.ScaleType.center) // 图片缩放方式
                        .size(ImageHolder.MATCH_PARENT, ImageHolder.WRAP_CONTENT) // 图片占位区域的宽高
                        .into(tvTrainDev); // 设置目标TextView

//                tvTrainDev.setText(Html.fromHtml(trainingPlan.getDescription())+"");
                ImageLoadUtils.ImageLoad(this,trainingPlan.getCoverUrl(),iv_pic,-1);

                List<TrainPlanDetail.TrainingPlanBean.PlanItemListBean> planItemList = trainingPlan.getPlanItemList();
                Map<String, TrainPlanDetail.PlanUserItemMap> planUserItemMap = data.getPlanUserItemMap();
                if(planUserItemMap!=null){
                    for (String key:planUserItemMap.keySet()){
                        TrainPlanDetail.PlanUserItemMap planUserItemMap1 = planUserItemMap.get(key);
                        for(int i=0;i<planItemList.size();i++){
                            if(null!=planUserItemMap1.getItemId() && planItemList.get(i).getItemId().equals(planUserItemMap1.getItemId())){
                                planItemList.get(i).setResult(planUserItemMap1.getResult());
                                planItemList.get(i).setExamId(planUserItemMap1.getExamId());
                                planItemList.get(i).setPlanUserItemId(planUserItemMap1.getId());
                            }
                        }
                    }
                }
                adapter.setNewData(planItemList);
                if(planItemList.size()>0 ){
//                    tvState
                    String result = planItemList.get(planItemList.size()-1).getResult();
                    if(result!=null && result.equals("pass")){
                        tvState.setText("已完成");
                        GradientDrawable background = (GradientDrawable) tvState.getBackground();
                        background.setColor(Color.parseColor("#24272D"));
                    }

                }
            }
        }
    }

    @Override
    public void setTaskCurriculumList(boolean isSuccess, int page, List<TaskCurriculumBean> data, String des) {
        
    }


}
